package org.platform.core.filecommand.util;



import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang3.StringUtils;


public class MyXmlHelper {
	
	public static final String XML_PREFIX = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
	//public static final String XML_PREFIX = "<?xml version=\"1.0\"?>\n";
	
	//private final static String RULE_PATH = "/config/bus/rule/";
	
	public static <T> T XmlToObject(String xmlString, Class<T> clazz) throws JAXBException {
		StringReader reader = new StringReader(xmlString);
		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		@SuppressWarnings("unchecked")
		T object = (T) unmarshaller.unmarshal(reader);
		return object;
	}
	
	public static String ObjectToXml(Object bean) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(bean.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
		StringWriter writer = new StringWriter();
		marshaller.marshal(bean, writer);
		String xmlString = StringUtils.join(XML_PREFIX,writer.getBuffer().toString());
		return xmlString;
	}
}
